package com.smart.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.smart.common.PageInfo;
import com.smart.common.domain.BaseEntity;
import com.smart.common.enums.*;
import com.smart.common.exception.BusinessException;
import com.smart.common.transfer.UnitTypeEnum;
import com.smart.common.utils.AssertUtil;
import com.smart.context.SessionContext;
import com.smart.mapper.*;
import com.smart.model.domain.*;
import com.smart.model.dtomapper.ProjectDtoMapper;
import com.smart.model.request.ProjectFileTaskInstanceRequest;
import com.smart.model.request.ProjectReportRequest;
import com.smart.model.request.ProjectRequest;
import com.smart.model.vo.UnReportVO;
import com.smart.service.ProjectReportService;
import com.smart.service.ProjectService;
import com.smart.model.convert.ProjectConvert;
import com.smart.model.vo.ProjectVO;
import com.smart.service.ProjectStatusAxisService;
import com.smart.service.ProjectUseControlService;
import com.smart.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.List;

import static com.smart.utils.PageUtils.getOrderBy;

/**
 * @author zyh
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, ProjectDO> implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectChangeReviewMapper projectChangeReviewMapper;
    @Autowired
    private ProjectReportService reportService;
    @Autowired
    private ProjectTempTaskServiceImpl tempTaskService;
    @Autowired
    private ProjectStatusAxisService axisService;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private ProjectUseControlService useControlService;
    @Autowired
    private ProjectFileTaskMapper projectFileTaskMapper;
    @Autowired
    private ProjectReportMapper projectReportMapper;
    @Autowired
    private ProjectFileTaskInstanceMapper projectFileTaskInstanceMapper;

    /**
     * 云监管项目详情和项目编辑回显查询
     *
     * @param id
     * @return
     */
    @Override
    public ProjectVO getByKey(Long id) {
        ProjectDO projectDO = getById(id);
        ProjectVO projectVO = ProjectDtoMapper.INSTANCE.do2VO(projectDO);
        return projectVO;
    }

    @Override
    public PageInfo<ProjectVO> pageQuery(ProjectRequest request) {
        long count = projectMapper.pageCount(request);
        List<ProjectDO> list = projectMapper.pageQuery(request, request.getPageSize(), request.fetchOffSet());
        List<ProjectVO> projectVOList = ProjectConvert.buildProjectVoList(list);
        return new PageInfo(request.getPageNum(), request.getPageSize(), projectVOList, count);
    }

    @Override
    public List<ProjectVO> listQuery(ProjectRequest request) {
        List<ProjectDO> list = list();
        List<ProjectVO> projectVOS = ProjectConvert.buildProjectVoList(list);
        return projectVOS;
    }

    @Override
    public List listProjectByStatus(List statusList) {
        List list = lambdaQuery().in(ProjectDO::getConstructionStatus, statusList).eq(ProjectDO::getValid, 1).eq(BaseEntity::getDeleted, 0).list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return ProjectConvert.buildProjectVoList(list);
    }

    /**
     * 云服务项目新增注册
     *
     * @param request
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String signIn(ProjectRequest request, HttpServletRequest req) {
        String message = asert(request, true);
        if (!org.springframework.util.ObjectUtils.isEmpty(message)) {
            return message;
        }
        List<String> allProjectAccount = projectMapper.selectAllProjectAccount(null);
        AssertUtil.assertTrue(!allProjectAccount.contains(request.getAccount()), "项目登录用户名已存在");
        String projectNumber = "001";
        List<String> defultProjectNumber = projectMapper.selectDefultProjectNumber();
        if (!org.springframework.util.ObjectUtils.isEmpty(defultProjectNumber)) {
            String max = Collections.max(defultProjectNumber, (a, b) -> Integer.compare(Integer.parseInt(a), Integer.parseInt(b)));
            Integer i = Integer.valueOf(max) + 1;
            projectNumber = String.format("%03d", i);
            request.setProjectNumber(projectNumber);
        }
        request.setProjectNumber(projectNumber);
        ProjectDO projectDO = ProjectDtoMapper.INSTANCE.request2DO(request);
        projectDO.setAuditStatus(ProjectAuditStatusEnum.WAIT.name());
        projectDO.setAuditType(ProjectAuditTypeEnum.NEW.name());
        projectDO.setValid(BooleanEnum.FALSE.getCode());
        projectDO.setCreateTime(DateUtils.getNowDate());
        projectDO.setUpdateTime(DateUtils.getNowDate());
        projectDO.setProjectNumber(request.getProjectNumber());
        projectDO.setDeleted(BooleanEnum.FALSE.getCode());
        projectMapper.insertDO(projectDO);
        UnitDO unitDO = new UnitDO();
        unitDO.setCreateTime(DateUtils.getNowDate());
        unitDO.setProjectId(projectDO.getId());
        unitDO.setUnitType(UnitTypeEnum.JIANSHE.getNewType());
        unitMapper.insertDO(unitDO);
        unitDO.setUnitType(UnitTypeEnum.JIANLI.getNewType());
        unitMapper.insertDO(unitDO);
        //写入数据提报功能初始化
        useControlService.save(build(projectDO));
        //短信发送
        SmsUtil.sendMessage(projectDO.getShigongContactPhone(), SmsTemplateEnum.SMS_463682027);
        return "新增成功";
    }

    private ProjectUseControlDO build(ProjectDO projectDO) {
        ProjectUseControlDO controlDO = new ProjectUseControlDO();
        controlDO.setProjectId(projectDO.getId());
        controlDO.setManageOpenStatus(OpenStatusEnum.UN_OPEN.name());
        controlDO.setReportOpenStatus(OpenStatusEnum.UN_OPEN.name());
        controlDO.setHotWorkOpenStatus(OpenStatusEnum.UN_OPEN.name());
        return controlDO;
    }

    /**
     * 云服务端项目编辑修改
     *
     * @param projectNow
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateByKey(ProjectRequest projectNow, HttpServletRequest req) {
        String message = asert(projectNow, false);
        if (!org.springframework.util.ObjectUtils.isEmpty(message)) {
            return message;
        }
        if (org.springframework.util.ObjectUtils.isEmpty(projectNow.getId())) {
            return "id不能为空";
        }
        //查询原信息
        Long projectId = projectNow.getId();
        if (org.springframework.util.ObjectUtils.isEmpty(projectId)) {
            projectId = SessionContext.getProjectId();
        }
        ProjectChangeReviewDO projectChangeReviewDO = new ProjectChangeReviewDO();
        ProjectDO projectOld = projectMapper.selectDOById(projectId);
        List<String> allProjectNumber = projectMapper.selectAllProjectNumber(projectId);
        List<String> allProjectAccount = projectMapper.selectAllProjectAccount(projectId);
        //查询是否存在编辑审核，如果还未审核完覆盖修改数据
        List<ProjectChangeReviewDO> changeReviewDO = projectChangeReviewMapper.selectDOByIProjectId(projectId);
        ProjectChangeReviewDO extracted = extracted(changeReviewDO);
        String number = projectNow.getProjectNumber();
        AssertUtil.assertTrue(!allProjectNumber.contains(number), "项目编号已存在");
        AssertUtil.assertTrue(!allProjectAccount.contains(projectNow.getAccount()), "项目登录用户名已存在");
        ProjectDO projectDO = ProjectDtoMapper.INSTANCE.request2DO(projectNow);
        ProjectDO aDo = projectMapper.selectDOById(projectId);
        if (aDo.getAuditType().equals(ProjectAuditTypeEnum.NEW.name()) && aDo.getAuditStatus().equals(ProjectAuditStatusEnum.WAIT.name())) {//如果是新项目待审核状态，修改直接成功
            projectMapper.updateDO(projectDO);
            return "修改成功";
        }
        Boolean haveChange = false;
        Boolean update = false;
        if (!org.springframework.util.ObjectUtils.isEmpty(projectNow.getConstructionStatus())) {
            if (!projectOld.getConstructionStatus().equals(projectNow.getConstructionStatus())) {
                projectChangeReviewDO.setConstructionStatusOld(projectOld.getConstructionStatus());
                projectChangeReviewDO.setConstructionStatusNow(projectNow.getConstructionStatus());
                if (!org.springframework.util.ObjectUtils.isEmpty(extracted)) {
                    String old = extracted.getConstructionStatusOld();
                    if (!org.springframework.util.ObjectUtils.isEmpty(old)) {
                        projectChangeReviewDO.setId(extracted.getId());
                        if (old.equals(projectNow.getConstructionStatus())) {//审核表中的旧值和新编辑修改的值一致的话，取消改字段的审核
                            projectChangeReviewDO.setConstructionAuditStatus(ProjectAuditStatusEnum.PASS.name());
                        }
                        projectChangeReviewDO.setConstructionStatusNow(extracted.getConstructionStatusNow());
                        update = true;
                    } else {
                        projectChangeReviewDO.setConstructionAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                    }
                } else {
                    projectChangeReviewDO.setConstructionAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                }
                haveChange = true;
            }
        }

        String shigongHeadNameOld = projectOld.getShigongHeadName();
        String shigongHeadNameNow = projectNow.getShigongHeadName();
        if (!org.springframework.util.ObjectUtils.isEmpty(shigongHeadNameNow)) {
            if (!shigongHeadNameOld.equals(shigongHeadNameNow)) {
                projectChangeReviewDO.setShigongHeadNameOld(shigongHeadNameOld);
                projectChangeReviewDO.setShigongHeadNameNow(shigongHeadNameNow);
                if (!org.springframework.util.ObjectUtils.isEmpty(extracted)) {
                    String old = extracted.getShigongHeadNameOld();
                    if (!org.springframework.util.ObjectUtils.isEmpty(old)) {
                        projectChangeReviewDO.setId(extracted.getId());
                        if (old.equals(projectNow.getShigongHeadName())) {
                            projectChangeReviewDO.setShigongHeadNameAuditStatus(ProjectAuditStatusEnum.PASS.name());
                        }
                        projectChangeReviewDO.setShigongHeadNameNow(extracted.getShigongHeadNameNow());
                        update = true;
                    } else {
                        projectChangeReviewDO.setShigongHeadNameAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                    }
                } else {
                    projectChangeReviewDO.setShigongHeadNameAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                }
                haveChange = true;
            }
        }

        String shigongHeadPhoneOld = projectOld.getShigongHeadPhone();
        String shigongHeadPhoneNow = projectNow.getShigongHeadPhone();
        if (!org.springframework.util.ObjectUtils.isEmpty(shigongHeadPhoneNow)) {
            if (!shigongHeadPhoneOld.equals(shigongHeadPhoneNow)) {
                projectChangeReviewDO.setShigongHeadPhoneOld(shigongHeadPhoneOld);
                projectChangeReviewDO.setShigongHeadPhoneNow(shigongHeadPhoneNow);
                if (!org.springframework.util.ObjectUtils.isEmpty(extracted)) {
                    String old = extracted.getShigongHeadPhoneOld();
                    if (!org.springframework.util.ObjectUtils.isEmpty(old)) {
                        projectChangeReviewDO.setId(extracted.getId());
                        if (old.equals(projectNow.getShigongHeadPhone())) {
                            projectChangeReviewDO.setShigongHeadPhoneAuditStatus(ProjectAuditStatusEnum.PASS.name());
                        }
                        projectChangeReviewDO.setShigongHeadPhoneNow(extracted.getShigongHeadPhoneNow());
                        update = true;
                    } else {
                        projectChangeReviewDO.setShigongHeadPhoneAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                    }
                } else {
                    projectChangeReviewDO.setShigongHeadPhoneAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                }
                haveChange = true;
            }
        }

        String contactNameOld = projectOld.getShigongContactName();
        String contactNameNow = projectNow.getShigongContactName();
        if (!org.springframework.util.ObjectUtils.isEmpty(contactNameNow)) {
            if (!contactNameOld.equals(contactNameNow)) {
                projectChangeReviewDO.setShigongContactNameOld(contactNameOld);
                projectChangeReviewDO.setShigongContactNameNow(contactNameNow);
                if (!org.springframework.util.ObjectUtils.isEmpty(extracted)) {
                    String old = extracted.getShigongContactNameOld();
                    if (!org.springframework.util.ObjectUtils.isEmpty(old)) {
                        projectChangeReviewDO.setId(extracted.getId());
                        if (old.equals(projectNow.getShigongContactName())) {
                            projectChangeReviewDO.setShigongContactNameAuditStatus(ProjectAuditStatusEnum.PASS.name());
                        }
                        projectChangeReviewDO.setShigongContactNameNow(extracted.getShigongContactNameNow());
                        update = true;
                    } else {
                        projectChangeReviewDO.setShigongContactNameAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                    }
                } else {
                    projectChangeReviewDO.setShigongContactNameAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                }
                haveChange = true;
            }
        }

        String contactPhoneOld = projectOld.getShigongContactPhone();
        String contactPhoneNow = projectNow.getShigongContactPhone();
        if (!org.springframework.util.ObjectUtils.isEmpty(contactPhoneNow)) {
            if (!contactPhoneOld.equals(contactPhoneNow)) {
                projectChangeReviewDO.setShigongContactPhoneOld(contactPhoneOld);
                projectChangeReviewDO.setShigongContactPhoneNow(contactPhoneNow);
                if (!org.springframework.util.ObjectUtils.isEmpty(extracted)) {
                    String old = extracted.getShigongContactPhoneOld();
                    if (!org.springframework.util.ObjectUtils.isEmpty(old)) {
                        projectChangeReviewDO.setId(extracted.getId());
                        if (old.equals(projectNow.getShigongContactName())) {
                            projectChangeReviewDO.setShigongContactPhoneAuditStatus(ProjectAuditStatusEnum.PASS.name());
                        }
                        projectChangeReviewDO.setShigongContactPhoneNow(extracted.getShigongContactPhoneNow());
                        update = true;
                    } else {
                        projectChangeReviewDO.setShigongContactPhoneAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                    }
                } else {
                    projectChangeReviewDO.setShigongContactPhoneAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                }
                haveChange = true;
            }
        }
        if (haveChange) {
            projectChangeReviewDO.setProjectId(projectId);
            if (update) {
                projectChangeReviewDO.setUpdateTime(DateUtils.getNowDate());
                projectChangeReviewDO.setUpdateUser(projectId);
                projectChangeReviewMapper.updateDO(projectChangeReviewDO);
                //查询状态是否全为PASS，是的话将项目从变更审核状态变为正常状态，如果是新项目注册未审核完毕则恢复为新注册未审核状态
                List<ProjectChangeReviewDO> changeReviewDOS = projectChangeReviewMapper.selectDOByIProjectId(projectId);
                ProjectChangeReviewDO reviewDO = extracted(changeReviewDOS);
                if (org.springframework.util.ObjectUtils.isEmpty(reviewDO)) {//为空则表示没有审核内容
                    projectDO.setAuditType(ProjectAuditTypeEnum.NORMAL.name());
                    projectDO.setAuditStatus(ProjectAuditStatusEnum.PASS.name());
                }else {
                    projectDO.setAuditType(ProjectAuditTypeEnum.CHANGE.name());
                    projectDO.setAuditStatus(ProjectAuditStatusEnum.WAIT.name());
                }
            } else {
                projectChangeReviewDO.setCreateTime(DateUtils.getNowDate());
                projectChangeReviewDO.setCreateUser(projectId);
                projectChangeReviewDO.setDeleted(BooleanEnum.FALSE.getCode());
                projectChangeReviewMapper.insertDO(projectChangeReviewDO);
                projectDO.setAuditType(ProjectAuditTypeEnum.CHANGE.name());
                projectDO.setAuditStatus(ProjectAuditStatusEnum.WAIT.name());
            }
        } else {
            projectDO.setAuditType(ProjectAuditTypeEnum.NORMAL.name());
        }
        projectDO.setUpdateTime(DateUtils.getNowDate());
        projectDO.setUpdateUser(projectId);
        projectMapper.cloudUpdateByKey(projectDO);
        return "修改成功";
    }

    private ProjectChangeReviewDO extracted(List<ProjectChangeReviewDO> changeReviewDO) {
        ProjectChangeReviewDO changeReview = changeReviewDO.stream().filter(review -> "WAIT".equals(review.getConstructionAuditStatus()) ||
                "WAIT".equals(review.getShigongContactNameAuditStatus()) ||
                "WAIT".equals(review.getShigongContactPhoneAuditStatus()) ||
                "WAIT".equals(review.getShigongHeadNameAuditStatus()) ||
                "WAIT".equals(review.getShigongHeadPhoneAuditStatus())).findFirst().orElse(null);
        return changeReview;
    }

    /**
     * 监管端项目编辑修改
     *
     * @param request
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String projectUpdateByKey(ProjectRequest request, HttpServletRequest req) {
        String message = asert(request, false);
        if (!org.springframework.util.ObjectUtils.isEmpty(message)) {
            return message;
        }
        if (org.springframework.util.ObjectUtils.isEmpty(request.getId())) {
            AssertUtil.assertTrue(false, "id不能为空");
        }
        String projectNumber = request.getProjectNumber();
        if (!org.springframework.util.ObjectUtils.isEmpty(projectNumber)) {
            AssertUtil.assertTrue(StringUtil.isValidProjectNumber(projectNumber), "项目编号为10位以内的字母或数字的组合");
        }
        int count = projectMapper.selectProNum(projectNumber, request.getId());
        AssertUtil.assertTrue(count < 1, "项目编号已存在");
        /**
         * 如果修改的是需编辑审核的字段：
         * ①先查询该项目是否处于编辑审核状态
         * ②如果不是直接修改成功
         * ③如果是则判断修改的字段值是否与编辑审核中被修改的值一致，如果一直则将该字段的审核置为通过，最后查询编辑审核字段是否已经全部审核通过，全部通过后修改项目状态
         */
        ProjectDO projectDO = ProjectDtoMapper.INSTANCE.request2DO(request);
        Long projectId = request.getId();
        ProjectDO doById = projectMapper.selectDOById(projectId);
        if (ProjectAuditTypeEnum.CHANGE.name().equals(doById.getAuditType())) {//项目处于编辑审核状态
            List<ProjectChangeReviewDO> changeReviewDOS = projectChangeReviewMapper.selectDOByIProjectId(projectId);
            ProjectChangeReviewDO extracted = extracted(changeReviewDOS);
            if (!org.springframework.util.ObjectUtils.isEmpty(extracted)) {
                ProjectChangeReviewDO reviewDO = new ProjectChangeReviewDO();
                reviewDO.setId(extracted.getId());
                String constructionStatusNow = extracted.getConstructionStatusNow();
                String contactNameNow = extracted.getShigongContactNameNow();
                String contactPhoneNow = extracted.getShigongContactPhoneNow();
                String headNameNow = extracted.getShigongHeadNameNow();
                String headPhoneNow = extracted.getShigongHeadPhoneNow();
                if (!org.springframework.util.ObjectUtils.isEmpty(constructionStatusNow)) {
                    if (constructionStatusNow.equals(request.getConstructionStatus())) {
                        reviewDO.setConstructionAuditStatus(ProjectAuditStatusEnum.PASS.name());
                    }
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(contactNameNow)) {
                    if (contactNameNow.equals(request.getShigongContactName())) {
                        reviewDO.setShigongContactNameAuditStatus(ProjectAuditStatusEnum.PASS.name());
                    }
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(contactPhoneNow)) {
                    if (contactPhoneNow.equals(request.getShigongContactPhone())) {
                        reviewDO.setShigongContactPhoneAuditStatus(ProjectAuditStatusEnum.PASS.name());
                    }
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(headNameNow)) {
                    if (headNameNow.equals(request.getShigongHeadName())) {
                        reviewDO.setShigongHeadNameAuditStatus(ProjectAuditStatusEnum.PASS.name());
                    }
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(headPhoneNow)) {
                    if (headPhoneNow.equals(request.getShigongHeadPhone())) {
                        reviewDO.setShigongHeadPhoneAuditStatus(ProjectAuditStatusEnum.PASS.name());
                    }
                }
                boolean empty = ObjectUtils.isFieldsEmpty(reviewDO, "id", "serialVersionUID");
                if (!empty) {
                    projectChangeReviewMapper.updateDO(reviewDO);
                    List<ProjectChangeReviewDO> changeReviewDOList = projectChangeReviewMapper.selectDOByIProjectId(projectId);
                    ProjectChangeReviewDO verify = extracted(changeReviewDOList);
                    if (org.springframework.util.ObjectUtils.isEmpty(verify)) {
                        projectDO.setAuditType(ProjectAuditTypeEnum.NORMAL.name());
                        projectDO.setAuditStatus(ProjectAuditStatusEnum.PASS.name());
                    }
                }
            }
        }


        projectDO.setUpdateUser(SessionContext.getSuperviseUserId());
        projectDO.setUpdateTime(DateUtils.getNowDate());
        try {
            projectMapper.updateDO(projectDO);
        } catch (DuplicateKeyException ex) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "项目编号已存在");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        String constructionStatus = request.getConstructionStatus();
        String aDoConstructionStatus = doById.getConstructionStatus();
        if (!"RUNNING".equals(aDoConstructionStatus) && !"WAIT_ACCEPT".equals(aDoConstructionStatus)) {
            if ("RUNNING".equals(constructionStatus) || "WAIT_ACCEPT".equals(constructionStatus)) {
                LocalDateTime now = LocalDateTime.now(); // 获取当前时间
                // 获取本周五的0点时间
                LocalDateTime fridayMidnight = now.with(DayOfWeek.FRIDAY).with(LocalTime.MIDNIGHT);
                if (now.isBefore(fridayMidnight)) {
                    //周报提报
                    reportService.createWeeklyTask(projectDO.getId());
                }
                //临时任务
                tempTaskService.createTempTask(projectDO.getId());
            }
        }
        AssertUtil.assertTrue((request.getAccount() != "" && request.getAccount() != null) ? doById.getAccount().equals(request.getAccount()) : true, "不能修改项目登录用户名");
        if (!org.springframework.util.ObjectUtils.isEmpty(constructionStatus)) {
            if (!constructionStatus.equals(aDoConstructionStatus)) {
                //变更施工状态时调用该接口，用于周报判断是否生成该项目的周报任务
                reportService.projectStatusChangeAdd(projectId, constructionStatus);
                //添加施工状态变更时间轴
                ProjectStatusAxisDO projectStatusAxisDO = new ProjectStatusAxisDO();
                projectStatusAxisDO.setProjectId(projectId);
                projectStatusAxisDO.setCreateTime(DateUtils.getNowDate());
                projectStatusAxisDO.setStatus(aDoConstructionStatus);
                projectStatusAxisDO.setCreateUser(SessionContext.getSuperviseUserId());
                axisService.save(projectStatusAxisDO);
            }
        }
        return "项目信息编辑成功";
    }


    @Override
    public ProjectDO selectByUserInfo(String account, String password) {
        return projectMapper.selectByUserInfo(account, password);
    }

    /**
     * 云管理-项目管理列表查询
     *
     * @param request
     * @param pageable
     * @return
     */
    @Override
    public Object selectMaProjectList(ProjectRequest request, Pageable pageable) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), getOrderBy(pageable.getSort())).setReasonable(true);
        Long jiansheUnitId = SessionContext.getJiansheUnitId();
        request.setProjectUnitId(jiansheUnitId);
        List<ProjectDO> projectDOList = projectMapper.selectProjectListByHeadInfo(request);
        com.github.pagehelper.PageInfo pageInfo = new com.github.pagehelper.PageInfo(projectDOList);
        List<ProjectVO> projectVOList = ProjectConvert.buildProjectVoList(projectDOList);
        pageInfo.setList(projectVOList);
        return pageInfo;
    }

    /**
     * 云管理项目详情查询
     *
     * @param id
     * @return
     */
    @Override
    public Object selectMaProjectDetail(Long id) {
        ProjectDO projectDO = projectMapper.selectDOById(id);
        projectDO.setJiansheHeadName(null);
        projectDO.setJiansheUnit(null);
        projectDO.setJiansheHeadPhone(null);
        projectDO.setAccount(null);
        projectDO.setPassword(null);
        projectDO.setProjectNumber(null);
        projectDO.setShigongContactPhone(null);
        ProjectVO projectVO = ProjectDtoMapper.INSTANCE.do2VO(projectDO);
        return projectVO;
    }

    @Override
    public ProjectVO queryProject(String code) {
        AssertUtil.assertNotNull(code, "项目编号/质量监督注册号不能为空");
        ProjectDO projectDO = projectMapper.queryProject(code);
        return ProjectDtoMapper.INSTANCE.do2VO(projectDO);
    }

    @Override
    public UnReportVO getUnReport() {
        Long projectId = SessionContext.getProjectId();
        UnReportVO reportVO = new UnReportVO();
        try {
            ProjectReportRequest request = new ProjectReportRequest();
            request.setProjectId(projectId);
            request.setItemType(ReportTypeEnum.WEEKLY.name());
            request.setStatus(0);
            long weekly = projectReportMapper.weeklyPageCount(request);
            reportVO.setWeekly(weekly);
        } catch (Exception ex) {
            log.error("查询周报未提报数据量异常 errorMsg={}", ex);
        }

        try {
            ProjectReportRequest request = new ProjectReportRequest();
            request.setItemType(ReportTypeEnum.TEMP.name());
            request.setProjectId(projectId);
            request.setStatus(0);
            long temp = projectReportMapper.tempPageCount(request);
            reportVO.setTemp(temp);
        } catch (Exception ex) {
            log.error("查询临时任务未提报数据量异常 errorMsg={}", ex);
        }

        try {
            ProjectFileTaskInstanceRequest request = new ProjectFileTaskInstanceRequest();
            request.setProjectId(SessionContext.getProjectId());
            request.setStatus(0);
            long file = projectFileTaskInstanceMapper.pageCount(request);
            reportVO.setFile(file);
        } catch (Exception ex) {
            log.error("查询文件未接收数据量异常 errorMsg={}", ex);
        }

        return reportVO;
    }

    @Override
    public Integer countOnlineProject() {
        return projectMapper.countOnlineProject();
    }

    @Nullable
    private String asert(ProjectRequest request, Boolean examine) {
        //新增校验必填字段是否为空
        if (examine) {
            String[] fields = ObjectUtils.addFields("projectIds", "projectUnitId", "projectInfo", "examine", "valid", "auditStatus", "auditType",
                    "constructionStatus", "projectNumber", "pageNum", "pageSize", "id", "updateUser", "updateUserName", "startUpdateTime", "endUpdateTime",
                    "createUser", "createUserName", "startCreateTime", "endCreateTime");
            if (ObjectUtils.isFieldsEmpty(request, fields)) {
                return "必填字段为空";
            }
        } else {//修改校验
            String[] fields = ObjectUtils.addFields("projectIds", "projectUnitId", "projectInfo", "examine", "valid", "auditStatus", "auditType",
                    "pageNum", "pageSize", "updateUser", "updateUserName", "startUpdateTime", "endUpdateTime",
                    "createUser", "createUserName", "startCreateTime", "endCreateTime");
            if (ObjectUtils.isFieldsEmpty(request, fields)) {
                return "必填字段为空";
            }
        }
        if (!org.springframework.util.ObjectUtils.isEmpty(request.getProjectName())) {
            AssertUtil.assertTrue(request.getProjectName().length() <= 300, "项目名称输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getAddress())) {
            AssertUtil.assertTrue(request.getAddress().length() <= 300, "详细地址输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getFloorArea())) {
            AssertUtil.assertTrue(StringUtil.isNumeric(request.getFloorArea().toPlainString()), "建筑面积输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getEngineeringCost())) {
            AssertUtil.assertTrue(StringUtil.isNumeric(request.getEngineeringCost().toPlainString()), "市政造价输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getQualityRegistrationNumber())) {
            AssertUtil.assertTrue(request.getQualityRegistrationNumber().length() <= 300, "质量监督注册号输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getShigongUnit())) {
            AssertUtil.assertTrue(request.getShigongUnit().length() <= 300, "施工单位输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getShigongHeadName())) {
            AssertUtil.assertTrue(request.getShigongHeadName().length() <= 50, "施工单位项目责任人姓名输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getShigongHeadPhone())) {
            AssertUtil.assertTrue(StringUtil.isPhoneNumber(request.getShigongHeadPhone()), "施工单位项目责任人手机号输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getShigongContactJob())) {
            AssertUtil.assertTrue(request.getShigongContactJob().length() <= 50, "施工单位项目联系人职务输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getAccount())) {
            AssertUtil.assertTrue(StringUtil.isValidPassword(request.getAccount()), "项目登录用户名输入有误");
        }

        if (!org.springframework.util.ObjectUtils.isEmpty(request.getPassword())) {
            AssertUtil.assertTrue(StringUtil.isValidPassword(request.getPassword()), "密码输入有误");
        }
        return null;
    }
}
